<template>
    <div>
        <!-- 导航栏 -->
        <van-nav-bar left-arrow @click-left="$router.back()" title="搜索中心" />
        <!-- 搜索栏 -->
        <van-search v-model="key" show-action placeholder="请输入搜索关键词" @search="onSearch" @input="doSuggest">
            <template #action>
                <div @click="onSearch">搜索</div>
            </template>
        </van-search>
        <!-- 联想词汇区域 -->
        <!-- 历史记录 -->
        <van-cell-group v-if="key==''">
          <van-cell title="历史记录" />
            <van-cell @click="fn(item)" v-for="(item,index) in historyList" :key="index" :title="item" />

        </van-cell-group>
          <!-- 搜索建议 -->
        <van-cell-group v-else>
            <van-cell v-for="(item,index) in colorList" :key="index" icon="search" >
                <template #title>
                  <div v-html="item" @click="fn(suggestList[index])"> </div>
                </template>>
            </van-cell>
        </van-cell-group>
    </div>
</template>

<script>
import { suggestAPI } from '@/api/search'

export default {
  name: 'MySearch',
  data () {
    return {
      key: '',
      suggestList: [],
      historyList: JSON.parse(localStorage.getItem('history95')) || []
    }
  },
  methods: {
    fn (item) {
      this.key = item
      this.onSearch()
      console.log(2)
    },
    onSearch () {
      if (this.key.trim() === '') return this.$toast('请输入搜索内容')
      const idx = this.historyList.indexOf(this.key)
      if (idx !== -1) {
        this.historyList.splice(idx, 1)
      }
      this.historyList.unshift(this.key)
      localStorage.getItem('history95', JSON.stringify(this.historyList))
      this.$router.push({
        name: 'SearchResult',
        query: {
          key: this.key
        }
      })
    },
    async doSuggest () {
      if (this.key.trim() === '') return
      const res = await suggestAPI({
        q: this.key
      })
      if (res.data.options[0] === null) {
        this.suggestList = []
      } else {
        this.suggestList = res.data.options
      }
    }
  },
  computed: {
    colorList () {
      return this.suggestList.map(v => {
        return v.replaceAll(this.key, `<span style="color:red;">${this.key}</span>`)
      })
    }
  }
}
</script>

<style></style>
